package org.example.aidemo.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.example.aidemo.pojo.Location;
import org.example.aidemo.pojo.Result;
import org.example.aidemo.service.UserService;
import org.example.aidemo.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.time.LocalDateTime;


@RestController
@RequestMapping("/api/location")
public class LocationController {
    @Autowired
    private SecurityUtils securityUtils;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Location> redisLocation;

    @PostMapping("/realtimeMsg")
    public Result<String> receiveRealtimeLocation(@RequestBody Location location,
                                                  HttpServletRequest request) {
        // 获取用户标识（可以从token或session中获取）
        String userId = getCurrentUserId();
        location.setId(Long.valueOf(userId));
        // 设置额外信息
        location.setIpAddress(request.getRemoteAddr());
        location.setUserAgent(request.getHeader("User-Agent"));
        location.setTimestamp(LocalDateTime.now());
        // 存储到Redis中（不持久化到数据库）
        redisLocation.opsForValue().set("user:location:" + userId, location, Duration.ofMinutes(5));

        return Result.success("位置信息接收成功");
    }

    @GetMapping("/current")
    public Result<Location> getCurrentLocation() {
        String userId = getCurrentUserId();
        Location location = redisLocation.opsForValue().get("user:location:" + userId);
        return Result.success(location);
    }

    private String getCurrentUserId() {
        // 根据你的认证方式实现用户ID获取逻辑
        String userid = userService.findByUsername(securityUtils.getCurrentUsername()).getId().toString();
        return userid;
    }
}